###############################################################################
#
# Copyright (C) 2007-TODAY Tiny ERP Pvt Ltd. All Rights Reserved.
#
# $Id$
#
# Developed by Tiny (http://openerp.com) and Axelor (http://axelor.com).
#
# The OpenERP web client is distributed under the "OpenERP Public License".
# It's based on Mozilla Public License Version (MPL) 1.1 with following
# restrictions:
#
# -   All names, links and logos of Tiny, Open ERP and Axelor must be
#     kept as in original distribution without any changes in all software
#     screens, especially in start-up page and the software header, even if
#     the application source code has been changed or updated or code has been
#     added.
#
# -   All distributions of the software must keep source code with OEPL.
#
# -   All integrations to any other software must keep source code with OEPL.
#
# If you need commercial licence to remove this kind of restriction please
# contact us.
#
# You can see the MPL licence at: http://www.mozilla.org/MPL/MPL-1.1.html
#
###############################################################################

from openerp.tools import expose
from openerp.tools import validate
from openerp.tools import error_handler
from openerp.tools import exception_handler

import cherrypy

from openerp import rpc
from openerp import cache
from openerp import tools
from openerp import widgets as tw

from openerp.utils import TinyDict

from form import Form
from form import get_validation_schema
from form import default_error_handler
from form import default_exception_handler

class OpenM2O(Form):

    path = '/openm2o'    # mapping from root

    @expose(template="templates/openm2o.mako")
    def create(self, params, tg_errors=None):

        params.editable = params.get('_terp_editable', True)
        params.hidden_fields = [tw.form.Hidden(name='_terp_m2o', default=params.m2o)]
        form = self.create_form(params, tg_errors)
        
        if not tg_errors:
            try:
                cherrypy.session.pop('remember_notebooks')
            except:
                self.reset_notebooks()

        editable = form.screen.editable
        mode = form.screen.view_type
        id = form.screen.id
        ids = form.screen.ids

        
        buttons = TinyDict()    # toolbar
        links = TinyDict()      # bottom links (customise view, ...)
        
        editable = True
        mode = 'form'
        
        buttons.saveandedit = False
        buttons.new =  editable or mode == 'tree'
        buttons.edit = not editable and mode == 'form'
        buttons.save = editable and mode == 'form'
        buttons.cancel = editable and mode == 'form'
        buttons.delete = editable and mode == 'form'
        buttons.pager =  mode == 'form' # Pager will visible in edit and non-edit mode in form view.

        buttons.search = 'tree' in params.view_mode and mode != 'tree'
        buttons.graph = 'graph' in params.view_mode and mode != 'graph'
        buttons.form = 'form' in params.view_mode and mode != 'form'
        buttons.calendar = 'calendar' in params.view_mode and mode != 'calendar'
        buttons.gantt = 'gantt' in params.view_mode and mode != 'gantt'
        buttons.can_attach = id and mode == 'form'
        buttons.has_attach = buttons.can_attach and len(form.sidebar.attachments)
        buttons.i18n = not editable and mode == 'form'
        
        target = getattr(cherrypy.request, '_terp_view_target', None)
        
        show_header = target != 'new'
        if not int(cherrypy.request.params.get('_terp_header_footer', 1)):
            show_header = False
        cherrypy.request.show_header_footer = show_header
            
        buttons.toolbar = target != 'new' and not form.is_dashboard

        if cache.can_write('ir.ui.view'):
            links.view_manager = True
            
        if cache.can_write('workflow'):
            links.workflow_manager = True
            
        buttons.process = cache.can_read('process.process')
        
        pager = None
        if buttons.pager:
            pager = tw.pager.Pager(id=form.screen.id, ids=form.screen.ids, offset=form.screen.offset,
                                   limit=form.screen.limit, count=form.screen.count, view_type=params.view_type)
        return dict(form=form, params=params, buttons=buttons, pager=pager, links=links, path=self.path, show_header_footer=show_header)
        #return dict(form=form, params=params,buttons=buttons)

    @expose()
    @validate(form=get_validation_schema)
    @error_handler(default_error_handler)
    @exception_handler(default_exception_handler)
    def save(self, terp_save_only=False, **kw):
        params, data = TinyDict.split(kw)

        # remember the current page (tab) of notebooks
        cherrypy.session['remember_notebooks'] = True

        # bypass save, for button action in non-editable view
        if not (params.button and not params.editable and params.id):

            proxy = rpc.RPCProxy(params.model)

            if not params.id:
                id = proxy.create(data, params.context)
                params.ids = (params.ids or []) + [int(id)]
                params.id = int(id)
                params.count += 1
            else:
                ctx = tools.context_with_concurrency_info(params.context, params.concurrency_info)
                id = proxy.write([params.id], data, ctx)

        button = (params.button or False) and True

        # perform button action
        if params.button:
            res = self.button_action(params)
            if res:
                return res

        current = params.chain_get(params.source or '')
        if current:
            current.id = None
            if not params.id:
                params.id = int(id)
        elif not button:
            params.editable = True

        if not current and not button:
            params.load_counter = 2
        
        params.editable = True
        
        return self.create(params)

    @expose()
    def edit(self, **kw):
        params, data = TinyDict.split(kw)

        if not params.model:
            params.update(kw)

        params.view_mode = ['form', 'tree']
        params.view_type = 'form'

        params.editable = params.get('_terp_editable', True)
        
        
        return self.create(params)
        
        
#        params, data = TinyDict.split(kw)
#
#        if not params.model:
#            params.update(kw)
#
#        params.view_mode = ['form', 'tree']
#        params.view_type = 'form'
#
#        params.editable = params.get('_terp_editable', True)
#
#        return self.create(params)

# vim: ts=4 sts=4 sw=4 si et

